package com.snatch.snatchmgr.core;


import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.snatch.common.vo.NodeTaskInput;
import com.snatch.common.vo.RatioDataInput;
import com.snatch.snatchmgr.service.ReceieveInnerDataService;
import com.snatch.snatchmgr.system.SystemData;
import com.snatch.snatchmgr.vo.NodeSnatch;
import com.snatch.snatchmgr.vo.SnatchItem;
import com.snatch.snatchmgr.vo.WebSnatchInfo;


@Component
@Scope ("prototype")
public class SnatchItemThread extends Thread{
	// 日志对象
		private Logger log = Logger.getLogger(SnatchItemThread.class);
	
	private NodeTaskInput nodeTaskInput;
	
	private boolean flag = true;
	
	private long sleepTime = 15;
	
	private long pastTime = 32*1000;
	
	@Autowired
	private ReceieveInnerDataService receieveInnerDataService;
	
	@Override
	public void run() {
		while (flag) {
			try {
				//bobo 后期做一定的逻辑  像atm存款一样，要求10个节点，就直接调度10个节点，如果有1个失败则重新调度一个节点执行任务。
				//receieveInnerDataService.snatchTask(nodeTaskInput);
				SnatchItem snatchItem  = SystemData.findSnatchItem(nodeTaskInput.getWebCode(), nodeTaskInput.getGameCode(),
						nodeTaskInput.getItemName(),nodeTaskInput.getItemType());
				snatchItem.setStart(1);
				for(int i = 0 ;i<snatchItem.getNodelist().size();i++){
					NodeSnatch nodesnatch = snatchItem.getNodelist().get(i);
					if((nodesnatch.getUpdateTiem()+pastTime)<System.currentTimeMillis()){
						snatchItem.getNodelist().remove(i);
					}
				}
				
				List<WebSnatchInfo>  webiniflist = receieveInnerDataService.findWebSnatchInfos(nodeTaskInput.getWebCode());
				if(null != webiniflist){
					for(WebSnatchInfo webSnatchInfo: webiniflist){
						if(webSnatchInfo.getValid()==2){
							if(!snatchItem.haveNode(webSnatchInfo.getOnlyCode())){
								nodeTaskInput.setOnlyCode(webSnatchInfo.getOnlyCode());
								nodeTaskInput.setValid(1);
								receieveInnerDataService.snatchTask(nodeTaskInput);
								NodeSnatch nodeSnatch = new NodeSnatch();
								nodeSnatch.setNodeOnlyCode(webSnatchInfo.getOnlyCode());
								nodeSnatch.setUpdateTiem(System.currentTimeMillis());
								snatchItem.getNodelist().add(nodeSnatch);
								
							}
						}
					}
				}
				//启动的总业务
				Thread.sleep(sleepTime*1000);
			} catch (Exception e) {
				log.error("出错！",e);
			}
		}
	}
	
	
	public void destroySnatchItemThread(){
		flag = false;
	}




	public NodeTaskInput getNodeTaskInput() {
		return nodeTaskInput;
	}


	public void setNodeTaskInput(NodeTaskInput nodeTaskInput) {
		this.nodeTaskInput = nodeTaskInput;
	}


	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}


	

}
